#!/usr/bin/perl # for syntax highlighting

use gri_secmgr qw(get_cookie_value got_cookie);
use gri_database;

sub mm_grant_document_section_access($$$$) {
my ($section,$user,$group,$type)=@_;

	my $v=get_cookie_value(name=>"gri_dbm_intranet");
	$v=~ s/\s+.*//;
	if($v eq "public") {
		print STDERR "mm_send_email: User logged in as public - no email sent!\n";
		return "Unable to grant access - user logged in as 'public'";
	}

	my $s2=hex_to_string($section); my $u2=hex_to_string($user);
	my $g2=hex_to_string($group); my $t2=$type;

	print STDERR "s2=$s2,g2=$g2,u2=$u2\n";
	my $db_dir=$::GRI_FRONTEND->get_global_directory("database");
	my $DB=new gri_database("$db_dir/gri.db");

	if($type eq "read") {
		$_e1=$DB->add_group_to_reader_list(group => $g2, section => $s2)
	} elsif($type eq "publish") {
		$_e1=$DB->add_group_to_publisher_list(group => $g2, section => $s2)
	} else {
		return "Error: Type of document specified is unexpected.";
	}

	if($_e1 !=1) {
		my ($a,$b);
		($a,$b)=$DB->error();
		if(defined($b)) {
			return "Error: Failed to update security information:<P>Error: $b.";
		}
		return "Error: Failed to update security information: Return code $_e1.";
	}

	#####################################################################
	# If we have granted access we also send the user an email			#
	# automatically indicating that we've granted them access.			#
	#####################################################################
	{
		my $email=$::GRI_FRONTEND->get_user_email_address($u2);
		my $admin_email=$::GRI_FRONTEND->get_user_email_address($v);
		if($email && $admin_email) {
			chomp $email;
			my $fd;
			open($fd,"|/usr/sbin/sendmail -t");
			print $fd "Mime-Version: 1.0\nContent-type: text/html; charset=\"iso-8859-1\"\n";
			print $fd "From: DBM Reporting Portal\n";
			print $fd "To: $email\n";
			print $fd "Subject: Request '$type' access to document section '$s2' - Granted!\n";
			print $fd "Cc: $admin_email\n\n";
			print $fd "Your access request specified above has been granted by '$admin_email'.\n";
			close($fd);
		}
		if(! $email) {
			return "Failed to send message - unable to resolve name '$v' to email address.";
		}
	}
	# Give a message indicating access has been granted...
	my $s="Access for user '$u2' has been granted. Click <a class=stdlink href=\"javascript:window.close();\">here</a> to close window.";
	return $s;
}

1;

# vim: ts=4:sw=4
